<template>
  <div>
    <el-dialog
     	title="分配小程序"
      :closeOnClickModal="false"
      :visible.sync="show"
      width="750px">
      <el-row>
      	<el-col :span="8">
      		帐号：{{data.userAccount}}
      	</el-col>
      	<el-col :span="8">
      		姓名：{{data.userName}}
      	</el-col>
      	<el-col :span="8">
          <el-switch
            v-model="type"
            :active-value="0"
            active-text="已分配"
            :inactive-value="1"
            inactive-text="未分配"
            >
          </el-switch>
      	</el-col>
      </el-row>
			<el-table
			   v-loading="!pload"
			   @selection-change = "selectionChange"
			    ref="multipleTable"
			    border
			    :data="tableData"
			    max-height="350"
			    style="margin-top: 15px;"
			   >
	        <el-table-column
	          type="selection"
	          width="55"
	          align="center"
	        >
	        </el-table-column>
			    <el-table-column
			      property="appletName"
			      label="小程序名称"
			      align="center"
			      show-overflow-tooltip
			      >
			    </el-table-column>
			    <el-table-column
			      property="userCount"
			      label="被分配数量"
			      align="center"
			      show-overflow-tooltip
			      width="100"
			      >
			    </el-table-column>
			    <el-table-column
			      label="到期时间"
			      align="center"
			      width="180"
			      show-overflow-tooltip
			      >
			      <template slot-scope="scope">
								{{scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}
			      </template>
			    </el-table-column>
			    <el-table-column
			    	v-if="!type"
			      label="最大可推送文章数"
			      align="center"
			      width="150"
			      show-overflow-tooltip
			      >
			      <template slot-scope="scope">
								<el-input-number v-model="scope.row.relationArticlesNumber" controls-position="right" @change="handleChange(scope.row)" :min="0" style="width: 120px;"></el-input-number>
			      </template>
			    </el-table-column>
			</el-table>
			
      <div style="padding-top: 10px; text-align: center;" v-loading="pload2">
        <el-button size="large" type="primary" @click="toggleOk" v-if="type" :disabled="selection < 1">确认分配</el-button>
        <el-button size="large" type="danger" @click="toggleCancel" v-else :disabled="selection < 1">取消分配</el-button>
      </div>
      
			<div class="pagination-container">
			  <el-pagination
			    @size-change="handleSizeChange"
			    @current-change="handleCurrentChange"
			    :current-page="currentPage"
			  :page-size="limit"
			  :page-sizes="limits"
			  background
			  layout="sizes, prev, pager, next, jumper, total"
			  :total="count">
			  </el-pagination>
			</div>
    </el-dialog>
  </div>
</template>
<script>
    import {weOwnApplet,weOwnAppletMaxArt,weOwnToApplet,weOwnCancelApplet} from '@/utils/weApi'
    import waves from '@/directive/waves' // 水波纹指令
    import debounce from 'throttle-debounce/debounce'
    import edit from './edit'
    export default {
      directives: {
        waves
      },
		  props: {
		    data: Object
		  },
      data(){
          return {
            tableData: [],
            search: {
              keyword: ''
            },
            type: 0,
            selection: [],
            selectTable: {},
            pload: false,
            pload2: false,
            show: true,
            currentPage:1,
            limit: 20,
            limits: [10,20,50,100],
            count:0
          }
      },
      components: {
        edit
      },
      created(){
         this.getData()
      },
		  watch: {
		    show (newVal) {
		      this.$parent.edit = false;
		    },
		    type (newVal) {
		      this.getData()
		    }
		  },
      methods: {
        selectionChange (selection) {
          this.selection = selection
        },
        toggleSelection(s) {
          if (!s) {
            this.tableData.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row)
            })
          } else {
            this.$refs.multipleTable.clearSelection()
          }
        },
        toggleOk () {
          this.$confirm('确认要分配吗',{type:'warning'}).then(async () => {
            let ids = this.selection.map((i,index) => {
              return i.appletId
            }).join(',')
            try{
              this.pload = false;
              await weOwnToApplet({
              	appletIds: ids,
        				agentId:this.data.userId
              })
              this.$notify({title: '分配成功', type: 'success', duration: 1000})
              this.getData()
            } catch(e) {
              this.pload = true;
            }
          })
        },
        toggleCancel () {
          this.$confirm('确认要取消分配吗',{type:'warning'}).then(async () => {
            let ids = this.selection.map((i,index) => {
              return i.appletId
            }).join(',')
            try{
              this.pload = false;
              await weOwnCancelApplet({
              	appletIds: ids,
        				agentId:this.data.userId
              })
              this.$notify({title: '取消分配成功', type: 'success', duration: 1000})
              this.getData()
            } catch(e) {
              this.pload = true;
            }
          })
        },
        handleChange : debounce(300,async function(n) {
        	console.log(n)
        	await weOwnAppletMaxArt({
        		appletId:n.appletId,
        		operableArticleCount: n.relationArticlesNumber,
        		agentId:this.data.userId
        	})
          this.$notify({title: '更新成功', type: 'success', duration: 5000})
        }),
		    async submitForm(formName) {
		      await this.$refs[formName].validate();
		      try {
		        this.pload = true
		        if (this.selectTable.method==='edit') {
		          await siteModify(this.selectTable)
		        }
		        else if (this.selectTable.method==='add') {
		          await siteSave(this.selectTable)
		        }
		        this.$notify({title: '操作成功', type: 'success', duration: 5000})
		        this.$parent.edit = false;
		        this.$emit('getData');
		      } catch(e) {
		        this.pload = false
		      }
		    },
        async getData(){
          if (this.search.date) {
            this.search.createTimeStart = this.search.date[0]
            this.search.createTimeEnd = this.search.date[1]
          } else {
            delete this.search.createTimeStart
            delete this.search.createTimeEnd
          }
          let data = this.JSONo(
	          {
	          	agentId: this.data.userId,
	          	status:this.type,
	            pageNum: this.currentPage,
	            pageSize: this.limit
	          },
          	this.search
          )
          this.pload = false
          const Datas = await weOwnApplet(data)
          this.tableData = Datas.data
          this.count = Datas.pageInfo.total
          this.pload = true
        },
        handleFilter () {
          this.getData()
        },
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`)
          this.limit = val
          this.getData()
        },
        handleCurrentChange(val) {
          this.currentPage = val
          this.getData()
        }
      }
    }
</script>